package com.study.spring.boot.study3.redis.config;

import com.yoloho.redis.RedisServiceImpl;
import com.yoloho.redis.api.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @author xuly
 * @title: CachConfig
 * @projectName spring-boot
 * @description: TODO
 * @date 2019-07-2617:32
 **/
@Configuration
@EnableCaching
@Slf4j

public class CachConfig extends CachingConfigurerSupport  {

    @Resource
    private RedisTemplate<String,String> redisTemplate;

//    @Bean
//    @Override
//    public CacheManager cacheManager() {
//        RedisCacheManager cacheManager = new RedisCacheManager();
//        return cacheManager;
//    }
//
//    @Bean
//    public RedisCacheManager cacheManager() {
//        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
//        return redisCacheManager;
//    }

    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName()).append(".");
                sb.append(method.getName()).append(".");
                for (Object obj : objects) {
                    sb.append(obj.toString());
                }
                log.info("keyGenerator=" + sb.toString());
                return sb.toString();
            }
        };
    }

    @Bean
    @Resource
    public RedisService redisService(StringRedisTemplate stringRedisTemplate) {
        RedisService redisService = new RedisServiceImpl();
        ((RedisServiceImpl) redisService).setRedisTemplate(stringRedisTemplate);
        return redisService;
    }

}
